package com.linked.basemanage.permissioncontrol.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.linked.basemanage.permissioncontrol.bean.param.AddMenusToPowerParam;
import com.linked.basemanage.permissioncontrol.bean.po.PowerMenuPO;
import com.linked.basemanage.permissioncontrol.bean.po.RolePowerPO;
import com.linked.basemanage.permissioncontrol.mapper.IPowerMenuMapper;
import com.linked.basemanage.permissioncontrol.service.IPowerMenusService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.time.LocalDateTime;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author :dbq
 * @date : 2023/2/23 15:32
 * @description : desc
 */
@Service
@Slf4j
public class PowerMenusServiceImpl implements IPowerMenusService {


    private final IPowerMenuMapper powerMenuMapper;

    private final ObjectMapper mapper;

    private final TransactionTemplate transactionTemplate;

    @Autowired
    public PowerMenusServiceImpl(IPowerMenuMapper powerMenuMapper, ObjectMapper mapper, TransactionTemplate transactionTemplate) {
        this.powerMenuMapper = powerMenuMapper;
        this.mapper = mapper;
        this.transactionTemplate = transactionTemplate;
    }

    @Override
    public boolean addMenusToPower(AddMenusToPowerParam param) throws Exception {
        LocalDateTime dateTime = LocalDateTime.now();
        return transactionTemplate.execute(action -> {
            try {
                AtomicInteger saveCount = new AtomicInteger(0);
                param.getMenuIds().stream().forEach(menuId -> {
                    PowerMenuPO temp = new PowerMenuPO();
                    temp.setPowerId(param.getPowerId());
                    temp.setMenuId(menuId);
                    temp.setCreateUserId(param.getUserId());
                    temp.setUpdateUserId(param.getUserId());
                    temp.setUpdateTime(dateTime);
                    saveCount.addAndGet(powerMenuMapper.insert(temp));
                });
                if (param.getMenuIds().size() != saveCount.get()) {
                    log.info("给权限加菜单接口，部分失败！");
                    action.setRollbackOnly();
                    return false;
                }
            } catch (Exception e) {
                log.error("给权限加菜单接口 异常！", e);
                action.setRollbackOnly();
                return false;
            }
            return true;
        });
    }
}

